// 用户相关的状态管理

import { getProfileAPI, loginAPI } from "@/apis/user";
import { getToken,setToken as _setToken, removeToken } from "@/utils";
import { createSlice } from "@reduxjs/toolkit";

const userStore = createSlice({
    name:"user",
    // 数据状态
    initialState:{
        token:getToken() || '',
        userInfo:{}
    },
    // 同步修改方法
    reducers:{
        setToken(state,action){
            state.token = action.payload
            // localStorage也存一份
            _setToken(action.payload)
        },
        setUserInfo(state,action){
            state.userInfo = action.payload
        },
        clearUserInfo(state){
            state.token = ''
            state.userInfo = {}
            removeToken()
        }
    }
})

//结构出actionCreater
const {setToken,setUserInfo,clearUserInfo} = userStore.actions

// 获取reducer函数
const userReducer = userStore.reducer

// 异步修改token
const fetchLogin = (loginForm) => {
    return async (dispatch)=>{
        // 发送异步请求
        const res = await loginAPI(loginForm)
        // 修改token
        dispatch(setToken(res.data.token))
    }
}
// 获取个人用户信息异步方法
const fetchUserInfo = () => {
    return async (dispatch)=>{
        // 发送异步请求
        const res = await getProfileAPI()
        // 修改token
        dispatch(setUserInfo(res.data))
    }
}
export {setToken,fetchLogin,setUserInfo,fetchUserInfo,clearUserInfo}

export default userReducer